package com.king.netty.dubbo.netty;

import com.king.netty.dubbo.customer.ClientBootstrap;
import com.king.netty.dubbo.provider.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 服务端 handler
 *
 * @Author king
 * @Date 2021-04-13 15:49
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 客户端在调用服务器的api时，需定义一个协议，例如每次发送的消息都必须以某个字符串开头 PROVIDER_NAME
        String str = msg.toString();
        System.out.println("NettyServerHandler 接收到的消息 = " + str);
        if (str.startsWith(ClientBootstrap.PROVIDER_NAME)) {
            // 获取客户端发送的消息，并调用服务
            String result = new HelloServiceImpl().hello(str.substring(str.lastIndexOf("#") + 1));
            // 回送消息
            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
